package hou.just4fun.HupuTweets.dao;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.stereotype.Component;

import hou.just4fun.HupuTweets.model.Tweet;
import hou.just4fun.HupuTweets.util.Md5Util;

/**
 * @author houweitao
 * @date 2016年5月6日 上午10:15:25
 */
@Component
public class TweetDao {
	private static final Logger log = LoggerFactory.getLogger(TweetDao.class);

	@Autowired
	@Qualifier("jdbcTemplate")
	private JdbcTemplate jdbcTemplate;

	public List<Tweet> listTenders() {
		List<Tweet> result = jdbcTemplate.query("SELECT * FROM tweet", new TweetMapper());
		return result;
	}

	public void saveTenderList(List<Tweet> tweets) {
		for (Tweet tweet : tweets)
			saveTweet(tweet);
	}

	public void saveTweet(Tweet tweet) {
		try {
			final Tweet t = tweet;
			jdbcTemplate.update("INSERT INTO tweet VALUES( ?, ?, ?, ? ,?,?)", new PreparedStatementSetter() {

				int p = 1;

				@Override
				public void setValues(PreparedStatement ps) throws SQLException {
					ps.setString(p++, Md5Util.getMd5(t.getUrl()));
					ps.setString(p++, t.getUrl());
					ps.setString(p++, t.getUser().getName());
					ps.setString(p++, t.getUser().getUrl());
					ps.setString(p++, t.getText());
					ps.setString(p++, t.getTime());
				}
			});
		} catch (Exception e) {
			log.error("...已经包含碎碎念..");
		}
	}

	public boolean check(Tweet tweet) {
		int num = jdbcTemplate
				.queryForInt("select COUNT(*) from tweet where id = '" + Md5Util.getMd5(tweet.getUrl()) + "'");

		if (num > 0)
			return true;
		else
			return false;
	}
}
